﻿using AdminWeb.Areas.Sys.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using SqlSugar;
using XW.Core;
using XW.Data;
using XW.Utils;
using XW.Web.Framework;
using XW.Web.Framework.Jwt;

namespace AdminWeb.Areas.Sys.Controllers
{
    /// <summary>
    ///  TODO  菜单管理控制器
    /// </summary>

    [Area("Sys")]
    [Authorize]
    public class ConfigController : BaseController
    {
        private readonly IOptions<JwtSecurityTokenOptions> _jwtOptions;
        private readonly ILogger<ConfigController> _logger;
        private readonly SqlSugarRepository<SysConfig> _configRep;

        public ConfigController(ILogger<ConfigController> logger, IOptions<JwtSecurityTokenOptions> jwtOptions, SqlSugarRepository<SysConfig> configRep)
        {
            _logger = logger;
            _jwtOptions = jwtOptions;
            _configRep = configRep;
        }
        /// <summary>
        /// 角色列表
        /// </summary>
        /// <returns></returns>
        public IActionResult List()
        { 
            return View();
        }
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> PageAsync()
        {
            var pageModel = CommonHelper.GetPageModel4Form<UserPageModel>();
            RefAsync<int> count = 0;
            var query = _configRep.AsQueryable();
            pageModel.Keyword = pageModel.Keyword.SafeTrim();
            // 关键字查询
            query.WhereIF(pageModel.Keyword.IsNotNullAndEmpty(),
                u => u.ConfigKey.Contains(pageModel.Keyword) || u.Title.Contains(pageModel.Keyword) || u.ConfigDes.Contains(pageModel.Keyword));

            // 排序
            if (pageModel.SortField.IsNotNullAndEmpty())
            {
                query.OrderByPropertyName(pageModel.SortField, pageModel.SortType == "desc" ? OrderByType.Desc : OrderByType.Asc);
            }
            // 排序
            var list = await query.ToPageListAsync(pageModel.Page, pageModel.Limit, count);

            return GetSuccessResult(new { items = list, count = count.Value });
        }


        /// <summary>
        /// 编辑
        /// </summary>
        /// <returns></returns>
        public IActionResult Edit(long id = 0)
        {
            SysConfig config = null;
            if (id > 0)
            {
                config = _configRep.GetById(id);
                if (config == null)
                {
                    return Content("<h1>数据不存在！</h1>");
                }
            }
            else
            {
                config = new SysConfig();
            }

            //ViewData["CurrentUser"] = user;
            return View(config);
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public IActionResult Save()
        {
            string? ConfigValue = this.Request.Form["ConfigValue"];

            long id = CommonHelper.ToInt64(this.Request.Form["id"]); 
            if (id == 0)
            {
                return GetErrorResult("不存在！");
                //string salt = RandomHelper.GetRandStr();
                //var role = new SysConfig();
                //role.Name = Name;
                //_configRep.Insert(role);
            }
            else
            {
                _configRep.AsUpdateable()
               .SetColumns(u => u.ConfigValue == ConfigValue)
               .setColumnsUpdateUserAndTime()
               .Where(u => u.Id == id).ExecuteCommand();
            }

            return GetSuccessResult("保存成功！");

        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> Delete(long id = 0)
        {
            SysConfig role = _configRep.GetById(id);
            if (role == null)
            {
                return GetErrorResult("角色不存在");
            }
            var result = await _configRep.DeleteByIdAsync(id);
            return GetSuccessResult("操作成功！");
        }
        /// <summary>
        /// 批量删除
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> BatDelete()
        {
            string ids = Request.Form["ids"];
            if (ids.IsNullOrEmpty())
            {
                return GetErrorResult("请选择需要删除的数据");
            }
            var idlist = ids.Split(',').Select(d => CommonHelper.ToInt64(d)).ToArray();
            var result = await _configRep.DeleteAsync(d => idlist.Contains(d.Id));
            return GetSuccessResult("操作成功！");
        }
    }
}
